package com.offcn.scwuser.service.impl;

import com.offcn.scwuser.enums.UserExceptionEnum;
import com.offcn.scwuser.exception.UserException;
import com.offcn.scwuser.mapper.TMemberAddressMapper;
import com.offcn.scwuser.mapper.TMemberMapper;
import com.offcn.scwuser.pojo.TMember;
import com.offcn.scwuser.pojo.TMemberAddress;
import com.offcn.scwuser.pojo.TMemberAddressExample;
import com.offcn.scwuser.pojo.TMemberExample;
import com.offcn.scwuser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private TMemberAddressMapper memberAddressMapper;
    @Autowired
    private TMemberMapper memberMapper;
    @Override
    public void registerUser(TMember member) {
       //判断账号是否存在
        TMemberExample example = new TMemberExample();
        example.createCriteria().andLoginacctEqualTo(member.getLoginacct());
        long l = memberMapper.countByExample(example);
        if (l>0){
            throw new UserException(UserExceptionEnum.LOGINaCCT_EXIST);
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(member.getUserpswd());
        member.setUserpswd(encode);
        //账号设置
        member.setUsername(member.getLoginacct());
        member.setAuthstatus("0");
        member.setUsertype("0");
        member.setAccttype("2");
        //设置账号信息
        memberMapper.insert(member);
       //数据传输不全,有选择性插入
        memberMapper.insertSelective(member);
    }
//登陆
    @Override
    public TMember login(String username, String password) {
        BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
        //  String encode1 = encode.encode(password);
        TMemberExample example = new TMemberExample();
        TMemberExample.Criteria criteria = example.createCriteria();
        criteria.andLoginacctEqualTo(username);
        //criteria.andUserpswdEqualTo(encode1);
        List<TMember> list = memberMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            TMember tMember = list.get(0);
            boolean matches = encode.matches(password, tMember.getUserpswd());//前面为加密，后参加密了两者进行对比
            if (matches) {
                return tMember;
            } else {
                return null;
            }
        }
return null;
    }

    @Override
    public List<TMemberAddress> findAddress(Integer memberId) {
        TMemberAddressExample example = new TMemberAddressExample();
        example.createCriteria().andMemberidEqualTo(memberId);
        return memberAddressMapper.selectByExample(example);
    }
}
